<template>
  <div class="user-roles-container">
    <div class="header">
      <h2>用户角色管理</h2>
      <button @click="showCreateModal = true" class="btn btn-primary">
        <i class="bx bx-plus"></i> 新增用户角色
      </button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-item">
        <label>用户ID:</label>
        <input v-model="searchForm.userId" placeholder="请输入用户ID" />
      </div>
      <div class="search-item">
        <label>角色代码:</label>
        <input v-model="searchForm.roleCode" placeholder="请输入角色代码" />
      </div>
      <div class="search-item">
        <label>角色名称:</label>
        <input v-model="searchForm.roleName" placeholder="请输入角色名称" />
      </div>
      <div class="search-item">
        <label>状态:</label>
        <select v-model="searchForm.status">
          <option value="">全部</option>
          <option value="ACTIVE">激活</option>
          <option value="INACTIVE">非激活</option>
          <option value="DELETED">已删除</option>
        </select>
      </div>
      <button @click="searchUserRoles" class="btn btn-secondary">
        <i class="bx bx-search"></i> 搜索
      </button>
      <button @click="resetSearch" class="btn btn-outline">
        <i class="bx bx-refresh"></i> 重置
      </button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>用户ID</th>
            <th>角色代码</th>
            <th>角色名称</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in userRoles" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.userId }}</td>
            <td>{{ item.roleCode }}</td>
            <td>{{ item.roleName }}</td>
            <td>
              <span :class="getStatusClass(item.status)">
                {{ getStatusText(item.status) }}
              </span>
            </td>
            <td>{{ formatDate(item.createdAt) }}</td>
            <td>
              <button @click="viewDetails(item)" class="btn btn-sm btn-info">
                <i class="bx bx-show"></i>
              </button>
              <button @click="editItem(item)" class="btn btn-sm btn-warning">
                <i class="bx bx-edit"></i>
              </button>
              <button @click="deleteItem(item.id)" class="btn btn-sm btn-danger">
                <i class="bx bx-trash"></i>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 创建/编辑模态框 -->
    <div v-if="showCreateModal || showEditModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑用户角色' : '新增用户角色' }}</h3>
          <button @click="closeModal" class="btn-close">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitForm">
            <div class="form-group">
              <label>用户ID:</label>
              <input v-model="form.userId" type="number" required />
            </div>
            <div class="form-group">
              <label>角色代码:</label>
              <input v-model="form.roleCode" required />
            </div>
            <div class="form-group">
              <label>角色名称:</label>
              <input v-model="form.roleName" required />
            </div>
            <div class="form-group">
              <label>状态:</label>
              <select v-model="form.status">
                <option value="ACTIVE">激活</option>
                <option value="INACTIVE">非激活</option>
                <option value="DELETED">已删除</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="submit" class="btn btn-primary">
                {{ showEditModal ? '更新' : '创建' }}
              </button>
              <button type="button" @click="closeModal" class="btn btn-secondary">
                取消
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 详情模态框 -->
    <div v-if="showDetailModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>用户角色详情</h3>
          <button @click="showDetailModal = false" class="btn-close">&times;</button>
        </div>
        <div class="modal-body">
          <div class="detail-item">
            <label>用户ID:</label>
            <span>{{ selectedItem.userId }}</span>
          </div>
          <div class="detail-item">
            <label>角色代码:</label>
            <span>{{ selectedItem.roleCode }}</span>
          </div>
          <div class="detail-item">
            <label>角色名称:</label>
            <span>{{ selectedItem.roleName }}</span>
          </div>
          <div class="detail-item">
            <label>状态:</label>
            <span :class="getStatusClass(selectedItem.status)">
              {{ getStatusText(selectedItem.status) }}
            </span>
          </div>
          <div class="detail-item">
            <label>创建时间:</label>
            <span>{{ formatDate(selectedItem.createdAt) }}</span>
          </div>
          <div class="detail-item">
            <label>更新时间:</label>
            <span>{{ formatDate(selectedItem.updatedAt) }}</span>
          </div>
          <div class="detail-item">
            <label>创建人:</label>
            <span>{{ selectedItem.createdBy || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>更新人:</label>
            <span>{{ selectedItem.updatedBy || '-' }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { userRolesApi } from '@/api/user-roles'

export default {
  name: 'UserRoles',
  data() {
    return {
      userRoles: [],
      searchForm: {
        userId: '',
        roleCode: '',
        roleName: '',
        status: ''
      },
      form: {
        userId: '',
        roleCode: '',
        roleName: '',
        status: 'ACTIVE'
      },
      showCreateModal: false,
      showEditModal: false,
      showDetailModal: false,
      selectedItem: {},
      editingId: null
    }
  },
  mounted() {
    this.loadUserRoles()
  },
  methods: {
    async loadUserRoles() {
      try {
        const response = await userRolesApi.getAllUserRoles()
        this.userRoles = response.data
      } catch (error) {
        console.error('加载用户角色失败:', error)
        alert('加载数据失败')
      }
    },

    async searchUserRoles() {
      try {
        let response
        if (this.searchForm.userId) {
          response = await userRolesApi.getUserRolesByUserId(this.searchForm.userId)
          this.userRoles = response.data
        } else if (this.searchForm.roleCode) {
          response = await userRolesApi.getUserRolesByRoleCode(this.searchForm.roleCode)
          this.userRoles = response.data
        } else if (this.searchForm.roleName) {
          response = await userRolesApi.getUserRolesByRoleName(this.searchForm.roleName)
          this.userRoles = response.data
        } else if (this.searchForm.status) {
          response = await userRolesApi.getUserRolesByStatus(this.searchForm.status)
          this.userRoles = response.data
        } else {
          this.loadUserRoles()
        }
      } catch (error) {
        console.error('搜索失败:', error)
        alert('搜索失败')
      }
    },

    resetSearch() {
      this.searchForm = {
        userId: '',
        roleCode: '',
        roleName: '',
        status: ''
      }
      this.loadUserRoles()
    },

    viewDetails(item) {
      this.selectedItem = item
      this.showDetailModal = true
    },

    editItem(item) {
      this.form = { ...item }
      this.editingId = item.id
      this.showEditModal = true
    },

    async deleteItem(id) {
      if (confirm('确定要删除这个用户角色吗？')) {
        try {
          await userRolesApi.deleteUserRoles(id)
          alert('删除成功')
          this.loadUserRoles()
        } catch (error) {
          console.error('删除失败:', error)
          alert('删除失败')
        }
      }
    },

    async submitForm() {
      try {
        if (this.showEditModal) {
          await userRolesApi.updateUserRoles(this.editingId, this.form)
          alert('更新成功')
        } else {
          await userRolesApi.createUserRoles(this.form)
          alert('创建成功')
        }
        this.closeModal()
        this.loadUserRoles()
      } catch (error) {
        console.error('提交失败:', error)
        alert('操作失败')
      }
    },

    closeModal() {
      this.showCreateModal = false
      this.showEditModal = false
      this.showDetailModal = false
      this.form = {
        userId: '',
        roleCode: '',
        roleName: '',
        status: 'ACTIVE'
      }
      this.editingId = null
    },

    getStatusClass(status) {
      const statusClasses = {
        'ACTIVE': 'status-active',
        'INACTIVE': 'status-inactive',
        'DELETED': 'status-deleted'
      }
      return statusClasses[status] || 'status-default'
    },

    getStatusText(status) {
      const statusTexts = {
        'ACTIVE': '激活',
        'INACTIVE': '非激活',
        'DELETED': '已删除'
      }
      return statusTexts[status] || status
    },

    formatDate(dateString) {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.user-roles-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.search-item label {
  font-weight: 500;
  font-size: 14px;
}

.search-item input,
.search-item select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background: #f8f9fa;
  font-weight: 600;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-outline {
  background: transparent;
  border: 1px solid #6c757d;
  color: #6c757d;
}

.btn-info {
  background: #17a2b8;
  color: white;
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.status-active {
  color: #28a745;
  font-weight: 500;
}

.status-inactive {
  color: #6c757d;
  font-weight: 500;
}

.status-deleted {
  color: #dc3545;
  font-weight: 500;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.detail-item label {
  font-weight: 500;
  min-width: 100px;
  margin-right: 10px;
}

.detail-item span {
  flex: 1;
}
</style> 